package com.zjzywl.smoke.controller;

/*
 * 微信f
 */
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.repository.CorridorRepository;
import com.zjzywl.smoke.repository.PictureRepository;
import com.zjzywl.smoke.util.WebResult;
import com.zjzywl.smoke.entity.Corridor;
import com.zjzywl.smoke.entity.Picture;

@RestController
@RequestMapping(value = "/content")
public class ContentController {
	@Autowired
	private PictureRepository repository;
	@Autowired
	private CorridorRepository corridorRepository;

	@RequestMapping("/save")
	public WebResult save(@RequestParam("picture") MultipartFile multipartFile, HttpServletRequest request) {
		if (multipartFile.isEmpty() || StringUtils.isBlank(multipartFile.getOriginalFilename())) {
			return WebResult.FAIL("图片数据为空！");
		}
		String contentType = multipartFile.getContentType();
		if (!contentType.contains("")) {
			return WebResult.FAIL("文件类型为空！");
		}
		String root_fileName = multipartFile.getOriginalFilename();
		// logger.info( root_fileName+contentType);

		String file_name = null;
		try {
			file_name = saveImg(multipartFile, "picture", root_fileName);

			if (StringUtils.isNotBlank(file_name)) {
				// 保存照片数据
				Picture cp = new Picture();
				String uuid = request.getParameter("uuid");
				String type = request.getParameter("type");
				cp.setUuid(uuid);
				cp.setType(type);
				cp.setFile("picture\\" + root_fileName);
				repository.save(cp);

				return WebResult.OK(file_name);
			}

		} catch (IOException e) {
			return WebResult.FAIL(e.getMessage());
		}
		return WebResult.FAIL("接收图片失败！");
	}

	/**
	 * 保存文件，直接以multipartFile形式
	 * 
	 * @param multipartFile
	 * @param path
	 *            文件保存绝对路径
	 * @return 返回文件名
	 * @throws IOException
	 */
	private static String saveImg(MultipartFile multipartFile, String path, String name) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
		String fileName = name;
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
		byte[] bs = new byte[1024];
		int len;
		while ((len = fileInputStream.read(bs)) != -1) {
			bos.write(bs, 0, len);
		}
		bos.flush();
		bos.close();
		return fileName;
	}

	private String getFilenameExcludeExpandedname(String filename) {
		String name = filename.substring(0, filename.indexOf('.'));
		return name;
	}

	/*
	 * 多文件上传
	 */
	@RequestMapping("/upload")
	public @ResponseBody String uploads(HttpServletRequest request, MultipartFile[] file) {
		try {
			// 上传目录地址
			String uuid = request.getParameter("uuid");
			String type = request.getParameter("type");
			String uploadDir = request.getSession().getServletContext().getRealPath("/") + "upload\\";
			System.out.println(uploadDir);
			// 如果文件不存在，自动创建文件夹
			File dir = new File(uploadDir);
			if (!dir.exists()) {
				dir.mkdir();
			}
			// 遍历文件数组执行上传方法
			for (int i = 0; i < file.length; i++) {
				if (file[i] != null) {
					// 调用上传方法
					executeUpload(uploadDir, file[i], uuid, type);
				}
			}
		} catch (Exception e) {
			// 打印出错
			e.printStackTrace();
			return "上传失败";
		}
		return "上传成功";
	}

	/*
	 * 图片上传方法
	 * 
	 */
	private void executeUpload(String uploadDir, MultipartFile file, String uuid, String type) throws Exception {
		// 文件后缀名
		String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
		// 上传文件名
		String filename = UUID.randomUUID() + suffix;
		// 服务器端报错的文件对象
		File serverFile = new File(uploadDir + filename);
		// 将上传到的文件写入到服务器
		file.transferTo(serverFile);
		// 保存照片数据
		Picture cp = new Picture();
		cp.setUuid(uuid);
		cp.setType(type);
		System.out.println(uploadDir);
		cp.setFile(uploadDir + filename);

		repository.save(cp);
	}

	/*
	 * 表单提交接口
	 */
	@RequestMapping("/form")
	public String formSubmit(Corridor corridor) {
		corridor.setTime(new Date());
		System.out.println(corridor.getAddress());
		corridorRepository.save(corridor);
		return null;

	}

	/*
	 * 获得照片
	 */
	@RequestMapping(value = "/getImg", method = RequestMethod.GET)
	public void doGetBackgroundImg(String type, String uuid, HttpServletResponse response) throws Exception {
		List<Picture> cp = repository.findByUuidAndType(uuid, type);
		System.out.println(cp.size());
		for (Picture picture : cp) {
			System.out.println(picture.getFile());
			String pictureFile = picture.getFile();
			response.setContentType("image/jpeg ");
			FileInputStream fis = new FileInputStream(pictureFile);
			OutputStream os = response.getOutputStream();
			try {
				int count = 0;
				byte[] buffer = new byte[1024 * 1024];

				while ((count = fis.read(buffer)) != -1) {
					os.write(buffer, 0, count);
				}

				os.flush();
			} catch (Exception e) {
				System.out.println("获取图片出错" + e);
			} finally {
				if (os != null)
					os.close();
				if (fis != null)
					fis.close();
			}
		}

	}
	// @RequestMapping("/login")
	// @ResponseBody
	// public Result getCode(HttpServletRequest request, HttpSession session){
	// //获取用户登录传过来的code
	// String code=request.getParameter("code");
	// System.out.println("code:"+code);
	// PreCode pre= preCodeManager.findCode();//获取第三方接口调用凭据
	// System.out.println("第三方接口调用凭据实体："+pre);
	// String grant_type="authorization_code";//固定值
	// //使用登录凭证 code 获取 session_key 和 openid。
	// Map<String,String> map=new HashMap<String,String>();
	// map.put("appid", appid);//小程序的appid
	// map.put("component_appid",WeChatContants.AppId);//第三方appid
	// map.put("js_code",code);//传入得用户code
	// map.put("grant_type",grant_type);
	// map.put("component_access_token",pre.getComponentAccessToken());
	// System.out.println("获取openid的url参数map为："+map);
	// String result="";
	// try {
	// result= HttpUtils.sendGet(WeChatContants.URL_WEIXIN_LOGIN_CODE,map);
	// System.out.println("获取openid结果为："+result);
	// } catch (Exception e) {
	// e.printStackTrace();
	// }
	// //解析返回的json数据，获得OPPID
	// Map<String,String> mps= JsonParse.getJsonStr(result);
	// String openid=mps.get("openid");
	// String session_key=mps.get("session_key");
	// Result returnResult = null;
	// if(openid!=null){
	// /*在此处添加自己的逻辑代码，将openid保存在数据库，或是，使用session_key去微信服务器换取用户头像、昵称等信息。我在这里并没有用到，因此我只保存了用户的openid*/
	//
	// }
	// return returnResult;
	// }
}
